import React from 'react'
import {
  Spin,
  Row,
  Col,
  Select,
  Tree,
  Input,
  Button,
  message,
  Tooltip,
} from 'antd'
import { createFromIconfontCN } from '@ant-design/icons'
import { emissionStandards, fuelType } from '../../utils/json'
import axios from 'axios'
import { checkres, deepClone } from 'utils'

const { TreeNode } = Tree
const { Search } = Input
const { Option } = Select

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1828145_e62n0tet9g5.js', // 在 iconfont.cn 上生成
})

function CarTree(props, ref) {
  const {
    compact,
    selectType,
    selectTreeId,
    showOline = false, //是否显示在线数量
    isloadData = true, //是否可以异步加载
    isG5 = false, //是否默认为国五
    isG6 = false, //是否默认为国六
  } = props
  const [loading, setLoading] = React.useState(false)
  const [seachData, setSeachData] = React.useState({
    vin: '',
    fuelType: '',
    emissionStandards: '',
  })
  const [seachFlag, setSeachFlag] = React.useState(false)
  const [expandedKeys, setExpandedKeys] = React.useState([])
  const [autoExpandParent, setAutoExpandParent] = React.useState(false)
  const [loadedKeys, setLoadedKeys] = React.useState([])
  const [selectedKeys, setSelectedKeys] = React.useState([])
  const [searchValue, setSearchValue] = React.useState('')
  const [treeData, setTreeData] = React.useState([])
  const [updateHandle, update] = React.useReducer(x => !x, false)

  React.useEffect(() => {
    setLoadedKeys([])
    if (isG5) setSeachData({ emissionStandards: '5' })
    if (isG6) setSeachData({ emissionStandards: 'a' })
    setLoading(true)
    axios
      .get('/region/tree', {
        params: { emissionStandards: isG5 ? '5' : isG6 ? 'a' : '' },
      })
      .then(res => {
        setLoading(false)
        if (!checkres(res)) return
        setTreeData(res.data.data)
      })
  }, [updateHandle])

  React.useImperativeHandle(ref, () => ({
    update,
  }))

  const seachTree = data => {
    console.log(data)
    setLoading(true)
    if (data.vin === '' || !data.vin) {
      axios
        .get('/region/tree', {
          params: { ...data, emissionStandards: isG5 ? '5' : isG6 ? 'a' : '' },
        })
        .then(res => {
          setLoading(false)
          if (!checkres(res)) return
          setTreeData(res.data.data)
          setSearchValue('')
          setExpandedKeys([])
        })
    } else {
      axios
        .get('/vehicle/getVehicleByVin', {
          params: {
            ...data,
            emissionStandards: isG5 ? '5' : isG6 ? 'a' : '',
          },
        })
        .then(res => {
          setLoading(false)
          if (!checkres(res)) return
          setExpandedKeys(res.data.data)
          setLoadedKeys([])
          setSearchValue(data.vin)
        })
    }
  }

  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys)
    setLoadedKeys(expandedKeys)
    setAutoExpandParent(false)
  }

  const onloadData = treeNode => {
    return new Promise(resolve => {
      if (treeNode.children) {
        resolve()
        return
      }
      axios
        .get('/vehicle/getVehicleList', {
          params: {
            ...seachData,
            areaCode: treeNode.dataRef.id,
          },
        })
        .then(res => {
          if (res.data.code == 1) {
            treeNode.dataRef.children = res.data.data
            const clonetreeData = deepClone(treeData)
            setTreeData(clonetreeData)
          } else {
            message.error('查询失败')
          }
          resolve()
        })
    })
  }

  const onSelect = (selectedKeys, info) => {
    if (selectedKeys.length == 0) {
      return false
    }
    if (
      isloadData &&
      (!info.node.props.dataRef.vin || info.node.props.dataRef.vin.length != 17)
    ) {
      message.warning('只能通过选择vin来查看列表')
      return false
    }
    console.log(selectedKeys, info.node.props.dataRef)
    selectTreeId(selectedKeys, info.node.props.dataRef)
    setSelectedKeys(selectedKeys)
  }

  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            style={{
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
            }}
            title={
              showOline ? (
                <Tooltip
                  title={
                    <span>{`在线：${item.onlineNum} 总计：${item.vehicleNum}`}</span>
                  }
                >
                  <span>
                    <span style={{ color: 'rgba(0,0,0,0.65)' }}>
                      {item.name}
                    </span>
                    <span style={{ color: '#46a3ff' }}>
                      {`(${item.onlineNum}/${item.vehicleNum})`}
                    </span>
                  </span>
                </Tooltip>
              ) : (
                item.name
              )
            }
            key={item.id}
            dataRef={item}
          >
            {renderTreeNodes(item.children)}
          </TreeNode>
        )
      }
      return (
        <TreeNode
          style={{
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
          }}
          title={
            <span
              style={{
                color:
                  item.name === searchValue
                    ? 'red'
                    : showOline
                    ? item.onlineStatus == 1
                      ? 'rgba(0,0,0,0.3)'
                      : 'rgba(0,0,0,0.65)'
                    : 'rgba(0,0,0,0.65)',
              }}
            >
              {item.name}
            </span>
          }
          icon={
            item.iconFontType === 2 ? (
              <>
                <MyIcon
                  style={{ fontSize: 18, marginRight: 2 }}
                  type={
                    item.emissionStandards === '5'
                      ? item.filingStatusG5 === 0
                        ? 'icon-wancheng-hui'
                        : 'icon-wancheng'
                      : item.filingStatus === 0
                      ? 'icon-wancheng-hui'
                      : 'icon-wancheng'
                  }
                />
                <MyIcon
                  style={{
                    fontSize: 18,
                    color: showOline
                      ? item.onlineStatus == 1
                        ? '#dddddd'
                        : '#46a3ff'
                      : 'rgba(0,0,0,0.65)',
                  }}
                  type={
                    item.emissionStandards
                      ? item.emissionStandards === '5'
                        ? 'icon-treeguowu-copy'
                        : 'icon-treeguoliu'
                      : 'icon-qiche-xian'
                  }
                />
                <MyIcon
                  style={{ fontSize: 18 }}
                  type={
                    item.oilGas === 'oil'
                      ? 'icon-ranyouche-mian'
                      : 'icon-ranqiche-mian'
                  }
                />
              </>
            ) : null
          }
          isLeaf={item.leaf}
          key={selectType == 'name' ? item.name : item.id}
          dataRef={item}
        />
      )
    })

  const seach = (
    <Row>
      <Col span={20}>
        <Search
          placeholder="输入vin"
          onSearch={value => {
            seachTree({ vin: value })
          }}
          value={seachData.vin}
          onChange={e => {
            setSeachData({ ...seachData, vin: e.target.value })
          }}
          style={{ width: '90%' }}
        />
      </Col>
      <Col span={4}>
        <a
          onClick={() => {
            setSeachFlag(true)
            setSeachData({
              ...seachData,
              emissionStandards: isG5 ? '5' : isG6 ? 'a' : '',
            })
          }}
        >
          展开
        </a>
      </Col>
    </Row>
  )
  const seachMore = (
    <Row>
      <Col span={20}>
        <Input
          placeholder="输入vin"
          value={seachData.vin}
          onChange={e => {
            setSeachData({ ...seachData, vin: e.target.value })
          }}
          style={{ width: '90%' }}
        />
      </Col>
      <Col span={4}>
        <a
          onClick={() => {
            setSeachFlag(false)
          }}
        >
          收起
        </a>
      </Col>
      <Col span={20}>
        <Select
          placeholder="选择排放标准"
          style={{ width: '90%', marginTop: 12 }}
          value={seachData.emissionStandards}
          onChange={value => {
            setSeachData({ ...seachData, emissionStandards: value })
          }}
          disabled={isG5 || isG6 ? true : false}
        >
          <Option key={9999} value="" disabled style={{ display: 'none' }}>
            选择排放标准
          </Option>
          {emissionStandards.map(item => (
            <Option key={item.value} value={item.value}>
              {item.name}
            </Option>
          ))}
        </Select>
      </Col>
      <Col span={20}>
        <Select
          placeholder="选择燃料类型"
          style={{ width: '90%', marginTop: 12 }}
          value={seachData.fuelType}
          onChange={value => {
            setSeachData({ ...seachData, fuelType: value })
          }}
        >
          <Option key={9999} value="" disabled style={{ display: 'none' }}>
            选择燃料类型
          </Option>
          {fuelType.map(item => (
            <Option key={item.value} value={item.value}>
              {item.name}
            </Option>
          ))}
        </Select>
      </Col>
      <Col span={20}>
        <div
          style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}
        >
          <Button
            type="primary"
            onClick={() => {
              seachTree(seachData)
            }}
          >
            查询
          </Button>
          <Button
            style={{ marginLeft: 12 }}
            onClick={() => {
              setSeachData({
                vin: '',
                fuelType: '',
                emissionStandards: isG5 ? '5' : isG6 ? 'a' : '',
              })
              seachTree({
                vin: '',
                fuelType: '',
                emissionStandards: isG5 ? '5' : isG6 ? 'a' : '',
              })
            }}
          >
            重置
          </Button>
        </div>
      </Col>
    </Row>
  )
  return (
    <Spin spinning={loading}>
      <div
        style={{
          paddingLeft: compact ? 12 : 0,
          marginTop: 12,
          marginBottom: 12,
        }}
      >
        {seachFlag ? seachMore : seach}
      </div>
      <Tree
        showIcon
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onSelect={onSelect}
        selectedKeys={selectedKeys}
        loadData={isloadData ? onloadData : null}
        loadedKeys={loadedKeys}
      >
        {renderTreeNodes(treeData)}
      </Tree>
    </Spin>
  )
}

export default React.forwardRef(CarTree)
